package com.onec.service.trade.service.online.quickpay;

import com.onec.service.api.dto.request.gateway.BizContent;
import com.onec.service.api.dto.response.BaseResponse;
import com.onec.service.api.dto.response.channel.ChannelTradeResp;
import com.onec.service.api.dto.response.customer.AgentInfoResp;
import com.onec.service.api.dto.response.customer.MerchantResp;
import com.onec.service.api.dto.response.route.RouteResp;
import com.onec.service.api.enums.StatusEnum;
import com.onec.service.api.utils.ValidatorUtils;
import com.onec.service.api.utils.group.trade.HtmlPayGroup;
import com.onec.service.trade.entity.BankInfo;
import com.onec.service.trade.entity.KBinInfo;
import com.onec.service.trade.entity.OnlineOrder;
import com.onec.service.trade.service.online.base.BaseOnlineDefaultService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * 快捷业务订单逻辑
 *
 * @author ONEC
 */
@Service("trade_html_pay")
public class HtmlPayService extends BaseOnlineDefaultService {

    private static final Logger logger = LoggerFactory.getLogger(HtmlPayService.class);

    /**
     * :trade_html_pay:
     *
     * @param bizContent 订单参数
     * @return BaseResponse
     */
    @Override
    public BaseResponse execute(BizContent bizContent) {
        ValidatorUtils.validateEntity(bizContent, HtmlPayGroup.class);
        logger.info("服务接口：，该服务实现中：");
        //机构信息gateway 已经验证： 需要验证商户信息：商户通道业务费率等
        MerchantResp merchantResp = getAvailableMerchant(bizContent.getMerchantNo(), bizContent.getBusinessNo());

        KBinInfo kBinInfo = kBinInfoService.getAvailableKBinInfo(bizContent.getCardNo());
        BankInfo bankInfo = bankInfoService.getAvailableBankInfo(kBinInfo.getBankCode());

        // risk： route：获取到路由通道：包含了通道业务编号：
        RouteResp routeResp = this.getRouteRiskTrade(bizContent, bankInfo.getBankCode());

        AgentInfoResp agentInfoResp = getAvailableAgentBusiness(bizContent.getAgentNo(), bizContent.getBusinessNo());

        // 检查是不是该机构下商户：
        isAgentNo(bizContent.getAgentNo(), agentInfoResp.getAgentCode());
        OnlineOrder onlineOrder = onlineOrderService.createOrder(merchantResp, routeResp, agentInfoResp, bizContent);

        ChannelTradeResp channelTradeResp = this.requestHtml(bizContent, onlineOrder);
        StatusEnum statusEnum = StatusEnum.FAILED;
        logger.info("通道：{}，支付结果描述：{}", routeResp.getChannelNo(), channelTradeResp.getMessage());
        if (channelTradeResp.isSuccess()) {
            statusEnum = StatusEnum.valueOf(channelTradeResp.getStatus());
        }
        onlineOrder = onlineOrderService.updateByTradeNum(channelTradeResp.getTradeNum(), statusEnum,
                channelTradeResp.getMessage());
        return respOrderResult(bizContent, onlineOrder);
    }
}
